package com.android.example.app3;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class MainActivity4 extends AppCompatActivity {

    private static final String TAG = "MainActivity4"; // 用于日志的TAG
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int PERMISSIONS_REQUEST_READ_STORAGE = 1001;
    private static final int PERMISSION_REQUEST_CODE = 100;
    private EditText textEditText;
    private EditText numberEditText;
    private EditText namingEditText;
    private Button saveButton;
    private Button namingButton;
    private TextView tvRules;
    private Button view_button;
    private Button clear_button;
    private Button gx_button;
    private TextView versionInfoTextView;
    private String downloadUrl; // 用于存储下载链接

    @SuppressLint({"MissingInflatedId", "SetJavaScriptEnabled"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化错误日志记录器
        ErrorLogger.getInstance(this).initialize();
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main4);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
//更新UI

        textEditText = findViewById(R.id.text_edit_text);
        numberEditText = findViewById(R.id.number_edit_text);
        namingEditText = findViewById(R.id.text_naming_text);
        saveButton = findViewById(R.id.save_button);
        namingButton = findViewById(R.id.naming_button);
        tvRules = findViewById(R.id.textViewRules);
        view_button = findViewById(R.id.view_button);
        clear_button = findViewById(R.id.clear_button);
        gx_button = findViewById(R.id.button);
        versionInfoTextView = findViewById(R.id.tv_version_info);

        //更新默认规则
        showRules();

        //点击事件
        saveButton.setOnClickListener(v -> saveData());
        namingButton.setOnClickListener(v -> namingData());
        view_button.setOnClickListener(v -> shareLogFile());
        clear_button.setOnClickListener(v -> clearLogFile());
        gx_button.setOnClickListener(v -> fetchVersionInfo());
        versionInfoTextView.setOnClickListener(v -> {
            if (downloadUrl != null && !downloadUrl.isEmpty()) {
                openDownloadLink(downloadUrl);
            } else {
                Toast.makeText(this, "下载链接无效", Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 打开下载链接
     *
     * @param url 下载地址
     */
    private void openDownloadLink(String url) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "无法打开链接: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void fetchVersionInfo() {
        GiteeApiHelper apiHelper = new GiteeApiHelper(new GiteeApiHelper.VersionInfoCallback() {


            @Override
            public void onSuccess(GiteeApiHelper.VersionInfo versionInfo) {
                // 在主线程更新UI
                runOnUiThread(() -> {
                    versionInfoTextView.setText(versionInfo.getDisplayText());
                    // 存储下载链接
                    downloadUrl = versionInfo.getDownloadUrl();
                });

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onError(String errorMessage) {
                runOnUiThread(() -> {
                    versionInfoTextView.setText("获取失败: " + errorMessage);
                    Toast.makeText(MainActivity4.this, errorMessage, Toast.LENGTH_SHORT).show();
                });
            }
        });
        apiHelper.getLatestVersionInfo();
    }
    private void shareLogFile() {
        File logFile = ErrorLogger.getInstance(this).getCurrentLogFilePath();
        if (logFile == null || !logFile.exists()) {
            Toast.makeText(this, "日志文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        // 使用 FileProvider 获取 Uri
        Uri fileUri = FileProvider.getUriForFile(this,
                getApplicationContext().getPackageName() + ".fileprovider", // 对应 AndroidManifest.xml 中的 authorities
                logFile);

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain"); // 或者 "text/plain;charset=utf-8"
        shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 授予接收者读取文件的临时权限

        // 检查是否有应用可以处理这个 Intent
        if (shareIntent.resolveActivity(getPackageManager()) != null) {
            startActivity(Intent.createChooser(shareIntent, "分享日志文件"));
        } else {
            Toast.makeText(this, "没有找到可以分享的应用", Toast.LENGTH_SHORT).show();
        }
    }

    private void clearLogFile() {
        boolean success = ErrorLogger.getInstance(this).clearAllLogs();
        if (success) {
            Toast.makeText(this, "日志已清除", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "清除日志时出错", Toast.LENGTH_SHORT).show();
        }
    }

    private void namingData() {
        String text = namingEditText.getText().toString().trim();
        // 检查输入框是否为空
        if (text.isEmpty()) {
            namingEditText.setError("单号开头不能为空");
            return; // 终止方法执行
        }
        addRuleToFile1(text);
        namingEditText.setText("");
    }
    private void saveData() {
        // 获取输入框的内容
        String text = textEditText.getText().toString().trim();
        String lengthStr = numberEditText.getText().toString().trim();
        // 检查输入框是否为空
        if (text.isEmpty()) {
            textEditText.setError("单号开头不能为空");
            return; // 终止方法执行
        }

        if (lengthStr.isEmpty()) {
            numberEditText.setError("单号总位数不能为空");
            return; // 终止方法执行
        }

        // 将字符串转换为整数
        int length;
        try {
            length = Integer.parseInt(lengthStr);
        } catch (NumberFormatException e) {
            numberEditText.setError("请输入有效的数字");
            return; // 终止方法执行
        }
        addRuleToFile(text, length);
        textEditText.setText("");
        numberEditText.setText("");
    }

    private void addRuleToFile1(String naming) {
        // 获取应用专属外部存储目录
        File externalFilesDir = getExternalFilesDir(null);
        // 检查外部存储目录是否存在
        if (externalFilesDir != null) {
            File rulesFile = new File(externalFilesDir, "naming.txt");
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(rulesFile, true))) {
                writer.write(naming);
                writer.newLine();
                writer.flush();
                // 调用 updateRulesFile 方法来更新规则文件
                ExpressNumberValidator.updateRulesFile(MainActivity4.this);
                // 更新 UI
                showRules();
            } catch (IOException e) {
                // 使用Log.e记录错误信息，确保您有一个TAG常量
                Log.e(TAG, "addRuleToFile: ", e);
            }
        } else {
            // 外部存储目录不可用，可以在这里处理错误或通知用户
            Log.e(TAG, "addRuleToFile: External storage directory is not available.");
        }
    }

    private void addRuleToFile(String prefix, int length) {
        // 获取应用专属外部存储目录
        File externalFilesDir = getExternalFilesDir(null);
        // 检查外部存储目录是否存在
        if (externalFilesDir != null) {
            File rulesFile = new File(externalFilesDir, "rules.txt");
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(rulesFile, true))) {
                writer.write(prefix + "," + length);
                writer.newLine();
                writer.flush();
                // 调用 updateRulesFile 方法来更新规则文件
                ExpressNumberValidator.updateRulesFile(MainActivity4.this);
                // 更新 UI
                showRules();
            } catch (IOException e) {
                // 使用Log.e记录错误信息，确保您有一个TAG常量
                Log.e(TAG, "addRuleToFile: ", e);
            }
        } else {
            // 外部存储目录不可用，可以在这里处理错误或通知用户
            Log.e(TAG, "addRuleToFile: External storage directory is not available.");
        }
    }

    @SuppressLint("SetTextI18n")
    private void showRules() {
        String guize = "null\n";
        String guize1 = "null\n";

        File externalFilesDir = getExternalFilesDir(null);
        File rulesFile = new File(externalFilesDir, "rules.txt");
        File namingFile = new File(externalFilesDir, "naming.txt");
        if (namingFile.exists()) {
            StringBuilder naming = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(namingFile))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    naming.append(line).append("\n");
                }
            } catch (IOException e) {
                naming.append("读取文件出错.");
            }
            guize1 = naming.toString();
        }


        if (rulesFile.exists()) {
            StringBuilder rules = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(rulesFile))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    rules.append(line).append("\n");
                }
            } catch (IOException e) {

                rules.append("读取文件出错.");
            }
            guize = rules.toString();

        }
        tvRules.setText("自定义规则：单号开头,单号总位数\n" +
                guize +
                "已排除规则\n" +
                guize1 +
                "默认规则：单号开头,单号总位数\n" +
                "JT,15\n" +
                "7,14\n" +
                "7,15\n" +
                "SF,15\n" +
                "YT,15\n" +
                "DPT,14\n" +
                "ZJS,15\n" +
                "JD,15\n" +
                "4,15\n");
    }

    // 检查并请求权限
    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_READ_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，执行相关操作
                showRules();
            } else {
                // 权限被拒绝，提示用户
                redirectToSettings();

            }
        }
    }

    // 显示权限解释对话框
    // 重定向到设置页面
    private void redirectToSettings() {
        new AlertDialog.Builder(this)
                .setMessage("我们需要读取存储权限来访问您的图片。请到设置中开启权限。")
                .setPositiveButton("去设置", (dialog, which) -> {
                    // 打开应用详情页面，引导用户开启权限
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    // 用户选择了取消，可以在这里降级应用的功能
                    Toast.makeText(this, "存储权限被拒绝，无法加载和保存自定义规则数据", Toast.LENGTH_LONG).show();
                })
                .create()
                .show();
    }

    // 输入框失去焦点时收起软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        View view = getCurrentFocus();
        if ((view instanceof EditText)) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        return super.dispatchTouchEvent(ev);
    }
}




